<!--
<template>
  <a-card :bordered="false">
    <a-form @submit="handleSubmit" :form="form">
      <a-col :md="24" :sm="24">
      <a-form-item label="Note" :labelCol="{ span: 7 }" :wrapperCol="{ span: 15 }">
        <a-input v-decorator="['note',{rules: [{ required: true, message: 'Please input your note!' }]}]"/>
      </a-form-item>
      </a-col>
      <a-col :md="24" :sm="24">
      <a-form-item label="Gender" :labelCol="{ span: 7 }" :wrapperCol="{ span: 15 }">
        <a-select v-decorator="['gender',{rules: [{ required: true, message: 'Please select your gender!' }]}]" placeholder="Select a option and change input text above" @change="this.handleSelectChange">
          <a-select-option value="male">male</a-select-option>
          <a-select-option value="female">female</a-select-option>
        </a-select>
      </a-form-item>
      </a-col>
      <a-col :md="24" :sm="24">
      <a-form-item label="Gender" :labelCol="{ span: 7 }" :wrapperCol="{ span: 15 }">
        <a-cascader :options="areaOptions" @change="onChange" :showSearch="{filter}" placeholder="Please select" />
      </a-form-item>
      </a-col>
      <a-form-item :wrapperCol="{ span: 12, offset: 5 }">
        <a-col :md="24" :sm="24">
          <a-form-item :wrapperCol="{ span: 12, offset: 5 }">
            <a-button type="primary" htmlType="submit">Submit</a-button>
          </a-form-item>
        </a-col>
      </a-form-item>
    </a-form>
  </a-card>
</template>

<script>
  import { getAction } from '@/api/manage'
  export default {
    data () {
      return {
        formLayout: 'horizontal',
        form: this.$form.createForm(this),
        areaOptions:[]
      }
    },
    methods: {
      handleSubmit (e) {
        e.preventDefault()
        this.form.validateFields((err, values) => {
          if (!err) {
            console.log('Received values of form: ', values)
          }
        })
      },
      handleSelectChange (value) {
        console.log(value)
        this.form.setFieldsValue({
          note: `Hi, ${value === 'male' ? 'man' : 'lady'}!`,
        })
      },
      onChange(value, selectedOptions) {
        console.log(value, selectedOptions);
      },
      filter(inputValue, path) {
        return (path.some(option => (option.label).toLowerCase().indexOf(inputValue.toLowerCase()) > -1));
      },
    },
    created (){
      getAction('/api/area').then((res) => {
          console.log("&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;&#45;")
          console.log(res)
          this.areaOptions = res;
      })
    }
  }
</script>-->



<template>
  <div>
    <div>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader"
                :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">上传</a-button>
      </a-upload>
      <a-button :disabled="isDisabled" @click="aaa">添加签章</a-button>
      <a-button :disabled="isDisabled" @click="addw">确定</a-button>
      <a-button :disabled="isDisabled" @click="previousPage">上一页</a-button>
      <a-button :disabled="isDisabled" @click="nextPage">下一页</a-button>
    </div>
    <div style="margin-left: 10%">
      <canvas id="c"></canvas>
    </div>
  </div>
</template>
<script>
  import Vue from 'vue'
  import { httpAction ,getAction,putAction,postAction} from '@/api/manage'
  import { ACCESS_TOKEN } from "@/store/mutation-types"


  let dom = null
  export default {
    name: 'TreatyContentPreview',
    data() {
      return {
        tokenHeader: {'X-Access-Token': Vue.ls.get(ACCESS_TOKEN)},
        caWidth: 792,
        caHeight: 612,
        canvas:{},
        //页数
        page:1,
        //文件名
        fileName:'',

        isDisabled:true,
      }
    },

    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${'graphics/upload'}`;
      }
    },
 /*   mounted() {
      this.canvas = new fabric.Canvas('c');
      this.canvas.setWidth(this.caWidth); //设置画布宽度
      this.canvas.setHeight(this.caHeight); //设置画布高度*!/

      /!**
       * 如何向画布添加一个Textbox对象？
       *!/
      /!* const textbox = new fabric.Textbox('这是一段文字', {
         left: 50,
         top: 50,
         width: 150,
         fontSize: 20, // 字体大小
         fontWeight: 800, // 字体粗细
         // fill: 'red', // 字体颜色
         // fontStyle: 'italic',  // 斜体
         // fontFamily: 'Delicious', // 设置字体
         // stroke: 'green', // 描边颜色
         // strokeWidth: 3, // 描边宽度
         hasControls: false,
         borderColor: 'orange',
         editingBorderColor: 'red' // 点击文字进入编辑状态时的边框颜色
       });
       this.canvasObj.add(textbox);

       var rect = new fabric.Rect({
         top: 100,
         left: 100,
         width: 60,
         height: 70,
         fill: 'red'
       });
       this.canvasObj.add(rect);*!/


     // var bg_url = "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
      var bg_url = "http://localhost:3000/hj/graphics/getImg"

      this.canvas.setBackgroundImage(bg_url, this.canvas.renderAll.bind(this.canvas), {
        width: this.canvas.getWidth(),
        height: this.canvas.getHeight(),
      });

      //console.log(JSON.stringify(canvas.toJSON()));
      console.log(this.canvas.getObjects());


    },
*/

    methods:{

      /*
      * 上传需要添加签章的文件，在后台将文件转换成图片
      * 判断文件上传是否成功，生成画布并且直接获取文件第一张的图片作为画布的背景图片
      * */
      handleImportExcel(info){
        if (info.file.status !== 'uploading') {
          console.log(info.file, info.fileList);
        }
        if (info.file.status === 'done') {
          if (info.file.response.success) {
            console.log(info.file.response.success, info.file.response.message);
            this.$message.success(`${info.file.name} 文件上传成功`);
            this.fileName=info.file.name;
            //生成画布
            this.createCanvas(this.fileName)

            this.isDisabled=false
          } else {
            this.$message.error(`${info.file.name} ${info.file.response.message}.`);
          }
        } else if (info.file.status === 'error') {
          this.$message.error(`文件上传失败: ${info.file.msg} `);
        }
      },

      //生成画布
      createCanvas(fileName){

        this.canvas = new fabric.Canvas('c');
        console.log(this.canvas);
        this.canvas.setWidth(this.caWidth); //设置画布宽度
        this.canvas.setHeight(this.caHeight); //设置画布高度
        //  //var bg_url = "https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png"
         let  bg_url = "http://localhost:3000/hj/graphics/getImg/"+fileName+"/"+this.page
        let img=this.getImgSize(bg_url)
        console.log(img)

        img.then(res => {
          console.log(res.width,res.height);
          console.log(this.canvas.getHeight(),this.canvas.getWidth());
          this.canvas.setBackgroundImage(bg_url, this.canvas.renderAll.bind(this.canvas), {
            //width: this.canvas.getWidth(),
            //height: this.canvas.getHeight(),
           scaleY: this.canvas.getHeight() / res.height,
           scaleX: this.canvas.getWidth() / res.width,
          });
        })

        // console.log(img.width,img.height);
        // this.canvas.setBackgroundImage(bg_url, this.canvas.renderAll.bind(this.canvas), {
        //   //width: this.canvas.getWidth(),
        //   //height: this.canvas.getHeight(),
        //  scaleY: this.canvas.getHeight() / img.height,
        //  scaleX: this.canvas.getWidth() / img.width,
        // });
        //
        // //console.log(JSON.stringify(canvas.toJSON()));
        // console.log(this.canvas.getObjects());
      },

      //获取图片的长宽
      getImgSize(bg_url){
        return new Promise(function(resolve, reject) {
          const image = new Image();
          image.onload = function() {
            resolve(image);
          };
          image.src = bg_url;
        });

      },


      aaa(){
        /*
        const textbox = new fabric.Textbox('这是一段文字', {
                 left: 50,
                 top: 50,
                 width: 150,
                 fontSize: 20, // 字体大小
                 fontWeight: 800, // 字体粗细
                 // fill: 'red', // 字体颜色
                 // fontStyle: 'italic',  // 斜体
                 // fontFamily: 'Delicious', // 设置字体
                 // stroke: 'green', // 描边颜色
                 // strokeWidth: 3, // 描边宽度
                 hasControls: false,
                 borderColor: 'orange',
                 editingBorderColor: 'red' // 点击文字进入编辑状态时的边框颜色
               });
               this.canvas.add(textbox);
               */

        this.rect = new fabric.Rect({
          top: 100,
          left: 100,
          width: 60,
          height: 70,
          fill: 'red'
        });
        this.canvas.add(this.rect)

        console.log(this.canvas.getObjects());
      },



      //获取图层信息
      bbb(){
        console.log(JSON.stringify(this.canvas.toJSON()));
        console.log(this.canvas.getObjects());
        console.log(this.canvas.getObjects().length);
        let obj= this.canvas.getObjects()

        //得到倾斜角度
        let angle=obj[0].angle
        console.log('倾斜角度：',angle)
        //得到三个点的坐标
        //左侧顶点的坐标
        let tl_x=obj[0].aCoords.tl.x
        console.log('x:',tl_x)
        let tl_y=obj[0].aCoords.tl.y
        console.log('y:',tl_y)
        let tr_x=obj[0].aCoords.tr.x
        let tr_y=obj[0].aCoords.tr.y
        let bl_x=obj[0].aCoords.bl.x
        let bl_y=obj[0].aCoords.bl.y

        let hh=Math.pow(tl_x,2)+Math.pow(bl_x,2)+Math.pow(tl_y,2)+Math.pow(bl_y,2)-2*tl_x*bl_x-2*tl_y*bl_y;
        //得到图层高度
        let h=Math.sqrt(hh)
        console.log('高度：',h);
        let ww=Math.pow(tl_x,2)+Math.pow(tr_x,2)+Math.pow(tl_y,2)+Math.pow(tr_y,2)-2*tl_x*tr_x-2*tl_y*tr_y;
        //得到图层长度
        let w=Math.sqrt(ww)
        console.log('长度：',w);

        return {
          x:tl_x,
          y:tl_y,
          angle:angle,
          w:w,
          h:h,
        }

      },


      addw(){
        let json=this.bbb();
        postAction("/graphics/addW" ,json).then(res => {
          if (res.success) {

          }
        })
      },
      //获取转换后的首张图片
      ccc(){
        getAction("/graphics/getPage").then(res => {
          if (res.success) {

          }
        })
      },

      //上一页
      previousPage(){
        if(this.page==1){
          this.$message.info('已经是第一页了');
          return
        }
        this.page=this.page-1;
        //生成画布
        this.createCanvas(this.fileName)

      },
      //下一页
      nextPage(){
        this.page=this.page+1;
        //生成画布
        this.createCanvas(this.fileName)
      },




    }


  }
</script>

<style lang='scss' scoped>

</style>